<?php

include "../index.php";


function we_test(){
    include('../function/wechat.php');
    if(isset($_GET['code'])){
        $wechat = new Wechat($GLOBALS['appid'],$GLOBALS['appsecret']);
       echo json($wechat->redircturl($_GET['code']));
        
    }else{
        $wechat = new Wechat($GLOBALS['appid'],$GLOBALS['appsecret']);
        $redirct_url=dirname(curPageURL())."/index.php?a=we_test";
        $wechat->granturl($redirct_url);
    }
}

function setaccess()
{
    session_start();
    if(!isset($_SESSION['tokenarr']))
    {
    $appid=$GLOBALS['appid'];
    $appsecret=$GLOBALS['appsecret'];
    $url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$appsecret}";
    $result=get_json($url);
    $tokenarr=json_decode($result,true);

    $_SESSION['tokenarr']=$tokenarr['access_token'];
    return $_SESSION['tokenarr'];
    }
    else{
    return $_SESSION['tokenarr'];

    }
}


function getmenu()
{
    $access_token=setaccess();
    p($access_token);
    $url="https://api.weixin.qq.com/cgi-bin/menu/get?access_token={$access_token}";
    p(get_json($url));
}

function granturl()
{
    setaccess();
    $appid=$GLOBALS['appid'];
    $redirct_url=dirname(curPageURL())."/index.php?a=redircturl";
    $redirct_url=urlencode($redirct_url);
    $url="https://open.weixin.qq.com/connect/oauth2/authorize?appid={$appid}&redirect_uri={$redirct_url}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
    return header("Location:{$url}");

}

function redircturl()
{
    $appid=$GLOBALS['appid'];
    $code=$_GET['code'];
    $appsecret=$GLOBALS['appsecret'];
    $url="https://api.weixin.qq.com/sns/oauth2/access_token?appid={$appid}&secret={$appsecret}&code={$code}&grant_type=authorization_code";
    $result=get_json($url);
    $data_access=json_decode($result,true);
    p($data_access);
    $url="https://api.weixin.qq.com/sns/userinfo?access_token={$data_access['access_token']}&openid={$data_access['openid']}&lang=zh_CN";
    $result=get_json($url);
    $data_user=json_decode($result,true);
    p($data_user);
}
